<template>
  <div class="Login_box">
    <div class="Login_box_top">
      <div class="Login_box_left">
        <div class="weather" v-for="(item, index) in weather" :key="index">
          <div class="currenTime">{{ item.city }}</div>
          <div class="currenTime">
            <img class="weatherIcon" style="width: 1.5625vw; height: 2.7778vh" :src="require('@/assets/weather/' + item.weather + '.png')" />
          </div>
          <div class="currenTime">{{ item.weather }}</div>
          <div class="currenTime">{{ item.temperature }}℃</div>
        </div>
      </div>
      <div class="Login_box_center">
        <img src="~@/assets/images/screen/logintitle.png" alt="" />
      </div>
      <div class="Login_box_right">
        <span class="currenTime"> {{ currentDate }}{{ currentTime }}</span>
      </div>
    </div>
    <div class="Login_box_buttom">
      <div class="Login_box_buttom_loding">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" :hide-required-asterisk="true" label-position="top">
          <div class="logintxt">
            <div>登录</div>
            <p></p>
          </div>
          <el-form-item prop="username" label="输入账号">
            <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="请输入您的账号" />
            <img v-show="isTick" class="tick" src="@/assets/images/tick.png" alt="" />
          </el-form-item>
          <el-form-item prop="password" label="输入密码">
            <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="请输入您的密码" @keyup.enter.native="handleLogin" />
            <img v-show="isTicks" class="tick" src="@/assets/images/tick.png" alt="" />
          </el-form-item>
          <el-form-item v-if="captchaEnabled" prop="identify">
            <el-input v-model="loginForm.identify" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter.native="handleLogin">
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <!-- <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox> -->
          <!-- <div class="forgot">
              <router-link class="link-type" :to="'/register'">忘记密码</router-link>
            </div> -->
          <el-form-item style="width: 100%">
            <el-button :loading="loading" size="medium" type="primary" @click.native.prevent="handleLogin">
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div v-if="register" style="float: right">
              <router-link class="link-type" :to="'/register'">立即注册</router-link>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <div class="Login_box_buttom_title">技术支持：山东省水利勘测设计院有限公司</div>
    </div>
  </div>
</template>
<script>
import jsonp from 'jsonp'
import { encrypt } from './index.js'
import { Message } from 'element-ui'
import { makeCode } from '@/utils'
export default {
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能小于6位'))
      } else {
        callback()
      }
    }
    const validateIdentify = (rule, value, callback) => {
      if (value.toLowerCase() !== this.identifyCode.toLowerCase()) {
        this.makeCode()
        callback(new Error('验证码错误'))
      } else {
        callback()
      }
    }
    return {
      weather: null,
      codeUrl: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: '',
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '账号不能为空' }],
        password: [
          {
            required: true,
            trigger: 'blur',
            message: '密码不能为空',
            // validator: validatePassword,
          },
        ],
        identify: [{ required: true, trigger: 'blur', validator: validateIdentify }],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: false,
      // 注册开关
      register: false,
      redirect: undefined,
      isTick: false,
      isTicks: false,
      stringval: '',
      style: {
        width: 1920 + 'px',
        height: 1080 + 'px',
        transform: 'scale(1) translate(-50%, -50%)',
      },
    }
  },
  mounted() {
    this.getWeathers()
    this.setScale()
    setInterval(this.updateClock, 1000)

    this.makeCode()

    window.addEventListener('resize', () => this.Debounce(this.setScale, 0))
  },
  methods: {
    passwordinput(e) {
      if (this.loginForm.password !== '') {
        var password = this.hashPassword(e)
        this.stringval = password
      }
    },
    Debounce: (fn, t) => {
      console.log(123)
      const delay = t || 500
      let timer
      console.log(123)

      const args = arguments
      if (timer) {
        clearTimeout(timer)
      }
      const context = this
      timer = setTimeout(() => {
        timer = null
        fn.apply(context, args)
      }, delay)
    },
    setScale() {
      this.style.transform = 'scaleX(' + window.innerWidth / 1920 + ') scaleY(' + window.innerHeight / 1080 + ')  translate(-50%, -50%)'
      console.log(this.style)
    },

    getCurrentTime() {
      const currentDate = new Date()
      const hours = currentDate.getHours()
      const minutes = currentDate.getMinutes()
      const seconds = currentDate.getSeconds()
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    },
    getCurrentDate() {
      const currentDate = new Date()
      const year = currentDate.getFullYear()
      const month = currentDate.getMonth() + 1
      const day = currentDate.getDate()
      const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
      const dayOfWeek = daysOfWeek[currentDate.getDay()]
      return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${dayOfWeek}`
    },
    updateClock() {
      this.currentTime = this.getCurrentTime()
      this.currentDate = this.getCurrentDate()
    },
    makeCode() {
      this.identifyCode = makeCode(4)
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if ((shiftKey && key >= 'a' && key <= 'z') || (!shiftKey && key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },

    hashPassword(passwored) {
      return encrypt(passwored)
    },

    handleLogin: function () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('permission/ResetPermissionsAndRoute')
          localStorage.setItem('username', JSON.stringify(this.loginForm.username))
          this.passwordinput(this.loginForm.password)
          const obj = {
            username: this.loginForm.username,
            password: this.stringval,
          }
          this.$store
            .dispatch('user/login', obj)
            .then((res) => {
              this.loading = false
              if (!this.$store.getters.token) {
                this.errorTime++
                this.makeCode()
                Message.error(res.data.msg)
                return
              }

              this.$router.push({
                path: this.redirect || '/',
                query: this.otherQuery,
              })
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getRandomArbitrary(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    // 获取天气
    getWeathers() {
      let that = this
      // TODO 济南市
      let citycode = '370100'
      // TODO 德州市
      // let citycode = '371400'
      jsonp(
        'https://restapi.amap.com/v3/weather/weatherInfo?key=ca5082172a271638aed2ea82d1cfab56&city=' + citycode + '&extensions=base',
        {
          name: 'success_jsonpCallback',
        },
        function (err, data) {
          console.log(data)
          that.weather = data.lives
        }
      )
    },
  },
}
</script>
<style lang="scss" scoped>
.Login_box {
  width: 100%;
  height: 100%;
  background-image: url('~@/assets/images/loginbg.png');
  background-size: 100% 100%;

  .Login_box_top {
    width: 100%;
    height: 7%;
    background: url('~@/assets/images/screen/组13.png');
    background-size: 100% 150%;
    display: flex;
    justify-content: space-between;

    .Login_box_left {
      width: 30vw;
      height: 6vh;
      font-size: 1vw;
      .weather {
        width: 20vw;
        height: 6vh;

        color: white;
        display: flex;
        align-items: center;
        .currenTime {
          padding: 0px 1vw;
        }
      }
    }

    .Login_box_center {
      width: 30vw;
      height: 6vh;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        width: 16vw;
      }
    }

    .Login_box_right {
      width: 30vw;
      height: 6vh;

      color: white;
      display: flex;
      align-items: center;
      justify-content: end;
      .currenTime {
        padding: 0px 1vw;
      }
    }
  }

  .Login_box_buttom {
    width: 100%;
    height: 93%;
    position: relative;

    .Login_box_buttom_loding {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 31.25vw;
      height: 31.25vw;
      // background-image: url('~@/assets/img/login/login4/logArea.png');
      background-size: 100% 100%;
      .login-form {
        height: 100%;
        padding: 4.4271vw 7.2917vw;
        background: linear-gradient(to bottom, rgba($color: #008d9b, $alpha: 0.7), rgba($color: #012d3a, $alpha: 0.7));
        border-radius: 15px;
        .logintxt {
          padding-bottom: 3.125vw;

          div {
            font-size: 2rem;
            line-height: 2.6667vh;
            color: #fff;
            font-weight: bold;
            padding-bottom: 1.25rem;
          }

          p {
            margin: 0;
            width: 3.875rem;
            height: 0.625rem;
            background-color: #fff;
            border-radius: 0.625rem;
          }
        }

        .el-input {
          height: 1.9792vh;

          input {
            height: 1.9792vh;
          }
        }

        .input-icon {
          height: 2.0313vh;
          width: 0.7292vw;
          margin-left: 0.1042vw;
        }

        .forgot {
          display: flex;
          justify-content: flex-end;
          padding: 1.0417vh 0 2.9167vw;

          a {
            color: #afb8e3;
          }
        }

        .el-form-item {
          margin-bottom: 0;
          margin-top: 2.8646vh;
          ::v-deep(.el-form-item__label) {
            color: #afb8e3 !important;
          }

          &:last-child {
            margin-bottom: 0;
            text-align: center;
          }

          .el-form-item__content {
            display: flex;
            align-items: center;
            position: relative;
            line-height: 2.5vh;

            .el-input {
              input {
                border-radius: 0;
                border: 0;

                color: #fff;
                padding-left: 0;
              }
            }

            .tick {
              position: absolute;
              right: 0;
              top: 8px;
            }

            .el-button--medium {
              margin: 0 auto;
              width: 80%;
              font-size: 1.625rem;
              background-color: #018a9a;
              border-radius: 1.875rem;
              border: 0;
              padding: 0.6771vh 0;
            }
          }
        }
      }
    }
    .Login_box_buttom_title {
      position: absolute;
      top: 90%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 19.75rem;
      color: white;
      text-align: center;
      //   font-size: ;
    }
  }
}
</style>
